;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.GiftOutInvoice", [])
        .controller("GiftOutInvoiceCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "$timeout", "$filter", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, $timeout, $filter) {
            $scope.activeFlag = [true, false];

            var btnPermissionCode = {
                giftOutInvoiceAudit: window.ActionCode.giftOutInvoiceAudit,
                giftOutInvoiceCreate: window.ActionCode.giftOutInvoiceCreate,
                giftOutInvoiceDel: window.ActionCode.giftOutInvoiceDel,
            };
            $scope.btnPermission = {
                giftOutInvoiceAudit: true,
                giftOutInvoiceCreate: true,
                giftOutInvoiceDel: true,
            };
            $scope.markInfo = {
                allChecked: false,
                curRow: -1
            };

            $scope.tabFlag = {};
            var tabFlag = {
                0: "开票申请",
                1: "编辑"
            };

            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.tableConfig = {
                scrollWidth: 1200,
                tableCol: [
                    {
                        name: "开票单号",
                        dataField: "invoiceNo",
                        type: "click",
                        width: 160,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "制单公司",
                        dataField: "orgName",
                        width: 160,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "制单人",
                        dataField: "createUserName",
                        width: 130,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "制单时间",
                        dataField: "createDate",
                        width: 130,
                        isShow: true,
                        toSort: false
                    },

                    {
                        name: "审核状态",
                        dataField: "auditStatus",
                        width: 130,
                        isShow: true,
                        toSort: false
                    },
                    {
                        name: "开票金额",
                        dataField: "invoiceAmount",
                        width: 130,
                        isShow: true,
                        toSort: false
                    },
                ]
            };

            //新增时左侧列表配置项
            $scope.addLeftTableConfig = {
                scrollWidth: 800,
                fixedWidth: 40,
                tableCol: [{
                        type: "",
                        name: "出库单号",
                        dataField: "exchangeOutNo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "兑换单号",
                        dataField: "exchangeNo",
                        width: 180,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createTime",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "出库仓库",
                        dataField: "outLocation",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "出库库区",
                        dataField: "outArea",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "出库时间",
                        dataField: "outboundDate",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "总价",
                        dataField: "totalPrice",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "客户姓名",
                        dataField: "customerName",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outboundStatus",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    }
                ]
            };

            $scope.newTbConfInvoice = {
                scrollWidth: 750,
                tableCol: [
                    {
                        type: "",
                        name: "兑换出库单号",
                        dataField: "exchangeOutNo",
                        width: 170,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "兑换单号",
                        dataField: "exchangeNo",
                        width: 170,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "零件号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDesc",
                        width: 170,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "零件单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "开票金额（元）",
                        dataField: "invoiceTotalPrice",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "开票单价（元）",
                        dataField: "invoiceUnitPrice",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "零件数量",
                        dataField: "num",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "开票系数",
                        dataField: "invoiceCoefficient", 
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "customerName",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                ]
            };


            $scope.orderPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };

            $scope.dataList = [];
            $scope.toolbarConfig = {};
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/sales-invoice-apply/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/sales-invoice-apply/exportAll")
            };
            $scope.condition = {};

            $scope.changeTab = function (index) {
                angular.forEach($scope.activeFlag, function (activeFlag) {
                    activeFlag = false;
                });
                $scope.activeFlag[index] = true;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        break;
                    default:
                        break;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
                $scope.orderObj = {};
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                    return;
                }
                $timeout(function () {
                    $scope.toolbarConfig["show" + toolbar] = true;
                });
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
                // $scope.condition.
            };

            $scope.selectAll = function () {
                for (var i = 0; i < $scope.dataList.length; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                getBillIds();
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.selectSingle = function (item) {
                var selectAll = false;
                if (!item.isChecked) {
                    selectAll = false;
                } else {
                    selectAll = checkAll($scope.dataList);
                }
                $scope.markInfo.allChecked = selectAll;
                getBillIds();
            };

            $scope.tdClick = function (item, fnType) {};

            $scope.stepList = {
                curStep: 0,
                list: [{
                    name: '选择发货通知单'
                }, {
                    name: '生成发运交接单'
                }]
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            /**
             *  高级搜索选项
             */
            $scope.condition = {
            }

            /**
             *  首页列表
             */
            function getDataList(curPage) {
                $scope.markInfo.curRow = -1;
                var service = "device",
                    reqUrl = "/giftExchangeInvoice/listInvoices",
                    param = {
                        pageSize: $scope.pageInfo.pageSize,
                        pageNum: $scope.pageInfo.curPage,
                        filters:$scope.condition
                    };

                if (!!curPage) {
                    param.pageNum = $scope.pageInfo.curPage = curPage;
                }

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {


                        item.createDate = $filter("YbDate")(item.createDate, df);
                        item.auditStatus = $filter("ProgressStatus")(item.auditStatus, "audit");
                        item.isChecked = false;

                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });

            }

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function initData() {
                $scope.markInfo.allChecked = false;
            }

            $scope.orderObj = {
                createDateStart: null,
                createDateEnd: null,
            };

            $scope.sign = function (id) {
                var service = "device";
                var reqUrl = "/invoice/sign";
                ybWidget.ShowConfirm("确定要签收吗？", "签收说明").then(function (note) {
                    var param = {
                        id: id,
                        signNote: note
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                });
            };

            // 编辑页
            $scope.edit = function (item) {
                    $scope.changeTab(1);
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.stepList.curStep = 1;
                    detailInfoFn(item.id);
            };


            // 开票申请
            $scope.updateSAP = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.changeTab(1);
                resetSAP();
                $scope.stepList.curStep = 0;
            };

            // 清空记忆数据
            function resetSAP() {
                $scope.condition.createDateStart = undefined;
                $scope.condition.createDateEnd = undefined;
                $scope.condition.auditTimeStart = undefined;
                $scope.condition.auditTimeEnd = undefined;
                $scope.orderDataList = [];
                $scope.newOrderObj = {
                    materialListShow: [],
                    materialListInvoice: [],
                };
            }

            // 审核
            $scope.examineId = '';
            $scope.examine = function (obj) {
                $scope.tabFlag.type = null;
                $scope.changeTab(2);
                detailInfoFn(obj.id);
            };

            $scope.newOrderObj = {
                materialListShow: [], // 显示零件列表
                materialListInvoice: [],
            };

            /**
             *  获取详情
             */
            function detailInfoFn(id) {
                var service = "device";
                var reqUrl = "/giftExchangeInvoice/item?id=" + id;
                return ybHttp.Get(service, reqUrl, "").then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    $scope.detailInfo = resp.value.headInfo;
                    $scope.newOrderObj.invoiceAmount = 0
                    angular.forEach(resp.value.details, function (item) {
                        $scope.newOrderObj.invoiceAmount = $scope.newOrderObj.invoiceAmount + item.invoiceTotalPrice;
                    });
                    $scope.newOrderObj.invoiceNo = resp.value.headInfo.invoiceNo;
                    $scope.newOrderObj.materialListInvoice = resp.value.details;
                    $scope.newOrderObj.customerName = resp.value.details[0].customerName;

                    $scope.newOrderObj.id = resp.value.headInfo.id;
                    $scope.newOrderObj.materialListInvoice = resp.value.details;
                    $scope.newOrderObj.customerName = resp.value.details[0].customerName;
                    $scope.examineId = id;
                });
            }

            /**
             *  详情页
             */
            $scope.detailPageFn = function (obj) {
                $scope.changeTab(6);
                detailInfoFn(obj.id);
            }


            /**
             *  审核
             *  0 通过      1 拒绝
             */
            $scope.auditSaveData = function (val) {
                var param = {
                    id: $scope.examineId,
                }
                var service = "device";
                
                var reqUrl = "/giftExchangeInvoice/auditReject";
                if(val == 0){
                    reqUrl = "/giftExchangeInvoice/auditPass";
                }
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            /**
             *  跳过
             */
            $scope.skip = function () {
                if ($scope.skipInfo.customerId == null) {
                    ybWidget.ShowMessage("未选择兑换出库单", MESG_TYPE.Error);
                    return false;
                }

                $scope.stepList.curStep = 2;
            };

            $scope.nextStep = function () {
                $scope.stepList.curStep = 1;

                var service = 'device';
                var reqUrl = '/giftExchangeInvoice/exchangeOutCreateInfo';
                var param = {
                    ids: [],
                };
                angular.forEach($scope.newOrderObj.materialListShow, function (item) {
                    param.ids.push(item.id)
                });
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.newOrderObj.invoiceAmount = 0
                    angular.forEach(resp.value.details, function (item) {
                        $scope.newOrderObj.invoiceAmount = $scope.newOrderObj.invoiceAmount + item.invoiceTotalPrice;
                    });
                    $scope.newOrderObj.materialListInvoice = resp.value.details;
                    $scope.newOrderObj.customerName = resp.value.details[0].customerName;
                })

            };

            $scope.upStep = function () {
                $scope.stepList.curStep = 0;
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.del = function (id) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/giftExchangeInvoice/remove";
                    var param = {
                        id :id
                    }
                    ybHttp.Get(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                })
            };

            $scope.datePickerFlag = [false, false];

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            // 无明细开票对象
            $scope.skipInfo = {
                customerId: null,
                customerName: null,
                money: null,
                remark: null
            }
            $scope.submit_skip = function () {

                if ($scope.skipInfo.money == null || $scope.skipInfo.money < 0) {
                    ybWidget.ShowMessage("申请开票金额为空或不合法", MESG_TYPE.Error);
                    return false;
                }

                var param = {
                    dealerOrgId: $scope.skipInfo.customerId,
                    dealerOrgName: $scope.skipInfo.customerName,
                    applyPrice: $scope.skipInfo.money,
                    remark: $scope.skipInfo.remark
                };
                save(param);

            };

            function save(param) {
                var service = "device";
                var reqUrl = "/sales-invoice-apply/simpleCreate";

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList(1);
                });
            }

            /**
             *  开票申请搜索
             */
            $scope.searchAddress = function () {
                $scope.newOrderObj.materialListShow = [];
                getSQDataList();
            };

            function getSQDataList(curPage) {
                $scope.markInfo.allChecked = true;
                if (!$scope.orderObj.customerName) {
                    ybWidget.ShowMessage('请先输入客户名称', MESG_TYPE.Error);
                    return;
                }
                var service = 'device';
                var reqUrl = '/giftExchangeInvoice/selectExchangeOuts';
                var param = {};

                param.pageSize = $scope.orderPageInfo.pageSize;
                param.pageNum = $scope.orderPageInfo.curPage;

                param.filters = $scope.orderObj

                if (!!curPage) {
                    param.pageNum = $scope.orderPageInfo.curPage = curPage;
                }

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var df = "yyyy-MM-dd HH:mm:ss";
                    angular.forEach(resp.value.list, function (item) {
                        item.createTime = $filter("YbDate")(item.createTime, df);
                        item.outboundDate = $filter("YbDate")(item.outboundDate, df);
                        item.outboundStatus = $filter("ProgressStatus")(item.outboundStatus, "outInvoice");
                        item.isChecked = false;

                        var index = $scope.newOrderObj.materialListShow.findIndex((function (item2) {
                            return item2.detailId == item.detailId
                        }))
                        if (index == -1) {
                            item.isChecked = false;
                            $scope.markInfo.allChecked = false;
                        } else {
                            item.isChecked = true;
                        }

                        item.adjustPrice = item.price;
                    });
                    $scope.orderPageInfo.totalRows = resp.value.total;
                    $scope.orderPageInfo.totalPages = resp.value.pages;
                    $scope.orderDataList = resp.value.list;
                })
            }

            /**
             * 开票申请 - 全选
             */
            $scope.orderSelectAll = function () {
                for (var i = 0; i < $scope.orderDataList.length; i++) {
                    $scope.orderDataList[i].isChecked = $scope.markInfo.allChecked;
                    if ($scope.markInfo.allChecked) {
                        if ($scope.newOrderObj.materialListShow.length > 0) {
                            var index = $scope.newOrderObj.materialListShow.findIndex((function (item2) {
                                return item2.id == $scope.orderDataList[i].id
                            }))
                            if (index == -1) {
                                $scope.newOrderObj.materialListShow.push($scope.orderDataList[i])
                            }
                        } else {
                            $scope.newOrderObj.materialListShow.push($scope.orderDataList[i])
                        }
                    }
                    if (!$scope.markInfo.allChecked) {
                        var index = $scope.newOrderObj.materialListShow.findIndex((function (item2) {
                            return item2.id == $scope.orderDataList[i].id
                        }))
                        if (index != -1) {
                            $scope.newOrderObj.materialListShow.splice(index, 1);
                        }
                    }
                }
                getOrderBillIds();
            };

            function getOrderBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.orderDataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            /**
             *  开票申请 - 复选框
             */
            $scope.orderSelectSingle = function (item) {
                var selectAll = false;
                if (!item.isChecked) {
                    selectAll = false;
                    delSelectedItem(item);
                } else {
                    $scope.newOrderObj.materialListShow.push(item);
                    selectAll = checkAll($scope.orderDataList);
                }
                $scope.markInfo.allChecked = selectAll;
                getBillIds();
            };


            /**
             * 删除右侧已选中的列表
             */
            function delSelectedItem(obj) {
                var index = $scope.newOrderObj.materialListShow.findIndex((function (item) {
                    return item.id == obj.id
                }))
                $scope.newOrderObj.materialListShow.splice(index, 1);
            }

            /**
             *  删除已选择的列表
             */
            $scope.delSelectItem = function (obj, index) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    $scope.newOrderObj.materialListInvoice.splice(index, 1);
                    $scope.newOrderObj.invoiceAmount = 0;
                    angular.forEach($scope.newOrderObj.materialListInvoice, function (item) {
                        $scope.newOrderObj.invoiceAmount = $scope.newOrderObj.invoiceAmount + item.invoiceTotalPrice;
                    });
                })
            };


            /**
             *  申请开票  提交
             */

            $scope.saveTicket = UserContextService.Debounce(function (argu) {
                _saveTicket(argu);
            }, 500);

            // 新增
            function _saveTicket() {
                if($scope.newOrderObj.materialListInvoice.length == 0){
                    ybWidget.ShowMessage("没有零件", MESG_TYPE.Error);
                    return;
                }
                var param = {
                    headInfo: {
                        invoiceNo: $scope.newOrderObj.invoiceNo ? $scope.newOrderObj.invoiceNo :"",
                        invoiceAmount: $scope.newOrderObj.invoiceAmount,
                        id :$scope.newOrderObj.id ? $scope.newOrderObj.id : ""
                    },
                    details: $scope.newOrderObj.materialListInvoice.map(function (item) {
                        delete item.exchangeOutOrgId
                        return item;
                    })
                }
                var service = "device";
                var reqUrl = "/giftExchangeInvoice/submit";
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    $scope.newOrderObj.invoiceNo = null;
                    $scope.newOrderObj.id = null;

                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            }

            (function () {
                if ($scope.isZHJCH) {
                    var newTableConfig = angular.copy($scope.tableConfig);
                    $scope.tableConfig.scrollWidth = 1540;
                    $scope.tableConfig.tableCol = [];
                    angular.forEach(newTableConfig.tableCol, function (item) {
                        if (item.type !== 'operate') {
                            $scope.tableConfig.tableCol.push(angular.copy(item));
                        }
                    });
                }

                getDataList(1);
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);
